package com.yiran.dao;

import java.sql.*;
import java.util.*;

import com.yiran.model.ProduceClass;
import com.yiran.util.DBConnection;

public class ProduceBean {
	private Connection con;
	ProduceClass produce = new ProduceClass();

	public ProduceBean() {
		try {
			con = DBConnection.getConnection();
			System.out.println("conn: " + con);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setProduceInfo(ProduceClass produce) {
		this.produce = produce;
	}

	public void addProduceInfo() throws Exception {
		try {

			PreparedStatement stm = con.prepareStatement("insert into produce(produceName) values(?)");
			stm.setString(1, produce.getName());

			try {
				stm.executeUpdate();
			} catch (Exception e) {
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public Collection getProduces() {
		ProduceClass produce;
		ArrayList arraylist = new ArrayList();
		try {
			Statement statement = con.createStatement();
			ResultSet resultset = statement.executeQuery("select * from produce");

			while (resultset.next()) {
				produce = new ProduceClass();
				int id = resultset.getInt(1);
				String name = resultset.getString(2);

				produce.setId(id);
				produce.setName(name);
				arraylist.add(produce);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return arraylist;
	}

	public ProduceClass getProduce(String pid) {
		ProduceClass produce;
		try {
			Statement statement = con.createStatement();
			ResultSet resultset = statement.executeQuery("select * from produce where produceId='"+pid+"'");

			while (resultset.next()) {
				produce = new ProduceClass();
				int id = resultset.getInt(1);
				String name = resultset.getString(2);

				produce.setId(id);
				produce.setName(name);
				return produce;
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void deleteProduce(String s) {
		try {
			int i = Integer.parseInt(s);
			Statement statement = con.createStatement();
			statement.execute("delete from produce where produceId='" + i + "'");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
